package org.dejlis.kurzycnb;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import android.os.AsyncTask;
import android.util.Log;

public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
	private static final String DEBUG_TAG = "HTTP Response";
	
	interface EventListener {
	    public void downloadFinished(String result);
	}
	
	private List<EventListener> listeners = new ArrayList<EventListener>();
	
	public void addListener(EventListener toAdd) {
		listeners.add(toAdd);
	}

	
	@Override
	protected String doInBackground(String... urls) {
        // params comes from the execute() call: params[0] is the url.            
		try {                
			return downloadUrl(urls[0]);            
		} catch (IOException e) 
		{                
			return "Unable to retrieve web page. URL may be invalid.";            
		}
	}

	private String downloadUrl(String myurl) throws IOException {
		// Given a URL, establishes an HttpUrlConnection and retrieves
		// the web page content as a InputStream, which it returns as string
		InputStream is = null;
		try {
			URL url = new URL(myurl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(10000 /* milliseconds */);
			conn.setConnectTimeout(15000 /* milliseconds */);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			// Starts the query
			conn.connect();
			int response = conn.getResponseCode();
			Log.d(DEBUG_TAG, "The response is: " + response);
			is = conn.getInputStream();
			// Convert the InputStream into a string
			String contentAsString = readIt(is);
			return contentAsString;
		} finally {
			if (is != null) {
				is.close();
			}
		}		
	}

	private String readIt(InputStream is) {
		String inputStreamString = new Scanner(is,"UTF-8").useDelimiter("\\A").next();
		return inputStreamString;
	}

	protected void onPostExecute(String result) {
		System.out.println("Download finished. Triggering event.");
		// Notify everybody that may be interested.
		for (EventListener el : listeners)
			el.downloadFinished(result);
		

	}
	
}
